package com.nulldev.util.crypto.api2.encryptors;

import java.nio.charset.Charset;

import com.nulldev.util.crypto.api2.Cryptable;
import com.nulldev.util.other.CharsetUtil;

public class LegacyXOR extends Cryptable{

	public LegacyXOR() {
		super("Legacy.XOR");
	}

	@Override
	public String encrypt(String object, String pass) {
		return this.encrypt(object, pass, CharsetUtil.getCharset());
	}

	@Override
	public String decrypt(String object, String pass) {
		return this.decrypt(object, pass, CharsetUtil.getCharset());
	}
	
	@Override
	public String encrypt(String object, String pass, Charset charset) {
		return xorMessage(object, pass);
	}

	@Override
	public String decrypt(String object, String pass, Charset charset) {
		return xorMessage(object, pass);
	}

    private static String xorMessage(String message, String key) {
        try {
            if (message == null || key == null) return null;
            char[] keys = key.toCharArray();
            char[] mesg = message.toCharArray();
            int ml = mesg.length;
            int kl = keys.length;
            char[] newmsg = new char[ml];
            for (int i = 0; i < ml; i++) {
                newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
            }
            return new String(newmsg);
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }

}
